package com.atguigu.gmall.item.controller;

import com.atguigu.gmall.item.lock.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lfy
 * @Description
 * @create 2023-08-21 11:28
 */
@Slf4j
@RestController
public class HelloLockController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedisLock redisLock;


    @Value("${server.port}")
    String port;

    //本地锁
    ReentrantLock lock = new ReentrantLock();


    @GetMapping("/incr")
    public String incr(){
        log.info("端口：{}，处理请求",port);
        String token = UUID.randomUUID().toString();
        try{
            redisLock.lock(token);
            //1、读数据
            String a = redisTemplate.opsForValue().get("a");
            int i = Integer.parseInt(a);
            //2、计算
            i++;
            //3、写数据
            redisTemplate.opsForValue().set("a",i+"");
        }finally {
            redisLock.unlock(token);
        }


        return "ok";
    }
}
